package com.qdlc.p2p.biz.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Hashtable;

/**
 * Created by hongbinglin on 2016/7/14.
 */
public class BitMapUtil {

    private static final int BLACK = 0xff000000;

    /**
     * 生成一个二维码图像
     *
     *            传入的字符串，通常是一个URL
     * @param widthAndHeight
     *           图像的宽高
     * @return
     */
    public static void createQRCode(String str, HttpServletResponse response, int widthAndHeight) throws WriterException,IOException {
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        BitMatrix matrix = new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight);
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        int[] pixels = new int[width * height];

        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                if (matrix.get(x, y)) {
                    pixels[y * width + x] = BLACK;
                }
            }
        }
        ServletOutputStream out = response.getOutputStream();
       try {
           BufferedImage image =  MatrixToImageWriter.toBufferedImage(matrix);
           ImageIO.write(image, "jpg", out);
           out.flush();
       }catch(Exception e){
           e.printStackTrace();
       } finally {
           out.close();
       }
    }
}
